<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>员工管理 - 员工信息管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
        }

        /* 头部样式 */
        .header {
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 15px 30px;
            margin-bottom: 20px;
        }

        .header-content {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 20px;
        }

        .header h1 {
            color: #409eff;
            font-size: 24px;
            flex: 0 0 auto;
        }

        .nav-menu {
            display: flex;
            gap: 10px;
            flex: 1;
            justify-content: center;
        }

        .nav-btn {
            padding: 8px 15px;
            background-color: #ecf5ff;
            color: #409eff;
            border: 1px solid #b3d8ff;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            font-size: 14px;
            transition: all 0.3s;
        }

        .nav-btn:hover {
            background-color: #409eff;
            color: #fff;
        }

        .nav-btn.active {
            background-color: #409eff;
            color: #fff;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 15px;
            flex: 0 0 auto;
        }

        /* 容器样式 */
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .card {
            background-color: #fff;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .card-title {
            font-size: 18px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #409eff;
        }

        /* 查询表单样式 */
        .search-form {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }

        .form-item {
            display: flex;
            flex-direction: column;
        }

        .form-item label {
            font-size: 14px;
            color: #606266;
            margin-bottom: 5px;
        }

        .form-item input,
        .form-item select {
            padding: 8px 12px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-item input:focus,
        .form-item select:focus {
            outline: none;
            border-color: #409eff;
        }

        /* 按钮样式 */
        .btn {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .btn-primary {
            background-color: #409eff;
            color: #fff;
        }

        .btn-primary:hover {
            background-color: #66b1ff;
        }

        .btn-success {
            background-color: #67c23a;
            color: #fff;
        }

        .btn-success:hover {
            background-color: #85ce61;
        }

        .btn-danger {
            background-color: #f56c6c;
            color: #fff;
        }

        .btn-danger:hover {
            background-color: #f78989;
        }

        .btn-default {
            background-color: #fff;
            color: #606266;
            border: 1px solid #dcdfe6;
        }

        .btn-default:hover {
            background-color: #ecf5ff;
            border-color: #409eff;
            color: #409eff;
        }

        .btn-group {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }

        /* 表格样式 */
        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 15px;
        }

        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ebeef5;
        }

        th {
            background-color: #f5f7fa;
            color: #606266;
            font-weight: 600;
        }

        tr:hover {
            background-color: #f5f7fa;
        }

        .table-actions {
            display: flex;
            gap: 8px;
        }

        .table-actions button {
            padding: 5px 10px;
            font-size: 12px;
        }

        /* 分页样式 */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 20px;
        }

        .pagination button {
            padding: 5px 10px;
            min-width: 35px;
        }

        .pagination span {
            color: #606266;
            font-size: 14px;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .modal.show {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: #fff;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
        }

        .modal-header {
            padding: 20px;
            border-bottom: 1px solid #ebeef5;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            font-size: 18px;
            color: #303133;
        }

        .close {
            font-size: 28px;
            font-weight: bold;
            color: #909399;
            cursor: pointer;
            line-height: 1;
        }

        .close:hover {
            color: #303133;
        }

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #ebeef5;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        /* 表单样式 */
        .modal-form .form-item {
            margin-bottom: 15px;
        }

        .modal-form .form-item input,
        .modal-form .form-item select {
            width: 100%;
        }

        .form-item.required label::after {
            content: " *";
            color: #f56c6c;
        }

        .error-message {
            color: #f56c6c;
            font-size: 12px;
            margin-top: 5px;
        }

        /* 单选按钮样式 */
        .radio-group {
            display: flex;
            gap: 15px;
            padding: 8px 0;
        }

        .radio-group label {
            display: flex;
            align-items: center;
            gap: 5px;
            cursor: pointer;
        }

        .radio-group input[type="radio"] {
            cursor: pointer;
        }

        /* 空数据提示 */
        .empty-data {
            text-align: center;
            padding: 50px;
            color: #909399;
        }

        /* 加载提示 */
        .loading {
            text-align: center;
            padding: 20px;
            color: #909399;
        }
    </style>
</head>
<body>
    <!-- 头部 -->
    <div class="header">
        <div class="header-content">
            <h1>员工信息管理系统</h1>
            <div class="nav-menu">
                <a href="employee.html" class="nav-btn active">员工管理</a>
                <a href="option.html" class="nav-btn">选项管理</a>
            </div>
            <div class="header-right">
                <!-- 未登录状态 -->
                <div id="notLoggedIn" style="display: none;">
                    <span style="color: #909399;">未登录</span>
                    <button class="btn btn-primary" onclick="goToLogin()">点击登录</button>
                </div>
                <!-- 已登录状态 -->
                <div id="loggedIn" style="display: none;">
                    <span id="username">欢迎您</span>
                    <button class="btn btn-default" onclick="logout()">退出登录</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 主内容 -->
    <div class="container">
        <!-- 查询区域 -->
        <div class="card">
            <div class="card-title">查询条件</div>
            <div class="search-form">
                <div class="form-item">
                    <label>姓名</label>
                    <input type="text" id="searchName" placeholder="请输入姓名">
                </div>
                <div class="form-item">
                    <label>手机号</label>
                    <input type="text" id="searchPhone" placeholder="请输入手机号">
                </div>
                <div class="form-item">
                    <label>性别</label>
                    <select id="searchGender">
                        <option value="">全部</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="form-item">
                    <label>岗位类型</label>
                    <select id="searchPositionType">
                        <option value="">全部</option>
                    </select>
                </div>
                <div class="form-item">
                    <label>入职开始日期</label>
                    <input type="date" id="searchHireDateStart">
                </div>
                <div class="form-item">
                    <label>入职结束日期</label>
                    <input type="date" id="searchHireDateEnd">
                </div>
                <div class="form-item">
                    <label>最低薪资</label>
                    <input type="number" id="searchSalaryMin" placeholder="请输入最低薪资">
                </div>
                <div class="form-item">
                    <label>最高薪资</label>
                    <input type="number" id="searchSalaryMax" placeholder="请输入最高薪资">
                </div>
            </div>
            <div class="btn-group">
                <button class="btn btn-primary" onclick="searchEmployees()">查询</button>
                <button class="btn btn-default" onclick="resetSearch()">重置</button>
            </div>
        </div>

        <!-- 表格区域 -->
        <div class="card">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <div class="card-title" style="margin-bottom: 0;">员工列表</div>
                <div class="btn-group" style="margin: 0;">
                    <button class="btn btn-success" onclick="showAddModal()">新增员工</button>
                    <button class="btn btn-danger" onclick="deleteBatch()">批量删除</button>
                </div>
            </div>
            
            <div class="table-container">
                <table id="employeeTable">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAll" onclick="toggleSelectAll()"></th>
                            <th>员工编号</th>
                            <th>姓名</th>
                            <th>年龄</th>
                            <th>性别</th>
                            <th>手机号</th>
                            <th>入职时间</th>
                            <th>岗位类型</th>
                            <th>薪资</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="employeeTableBody">
                        <tr><td colspan="10" class="loading">加载中...</td></tr>
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            <div class="pagination">
                <button class="btn btn-default" onclick="changePage(1)">首页</button>
                <button class="btn btn-default" onclick="changePage(currentPage - 1)">上一页</button>
                <span>第 <span id="currentPageDisplay">1</span> / <span id="totalPagesDisplay">1</span> 页</span>
                <button class="btn btn-default" onclick="changePage(currentPage + 1)">下一页</button>
                <button class="btn btn-default" onclick="changePage(totalPages)">末页</button>
                <span style="margin-left: 20px;">共 <span id="totalRecordsDisplay">0</span> 条记录</span>
            </div>
        </div>
    </div>

    <!-- 新增/编辑模态框 -->
    <div id="employeeModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">新增员工</h3>
                <span class="close" onclick="closeModal()">&times;</span>
            </div>
            <div class="modal-body">
                <form id="employeeForm" class="modal-form">
                    <input type="hidden" id="employeeId">
                    
                    <div class="form-item required">
                        <label>姓名</label>
                        <input type="text" id="empName" placeholder="请输入姓名">
                    </div>
                    
                    <div class="form-item required">
                        <label>年龄</label>
                        <input type="number" id="empAge" placeholder="请输入年龄（18-100）" min="18" max="100">
                    </div>
                    
                    <div class="form-item required">
                        <label>性别</label>
                        <div class="radio-group">
                            <label><input type="radio" name="gender" value="男" checked> 男</label>
                            <label><input type="radio" name="gender" value="女"> 女</label>
                        </div>
                    </div>
                    
                    <div class="form-item required">
                        <label>手机号</label>
                        <input type="text" id="empPhone" placeholder="请输入手机号">
                    </div>
                    
                    <div class="form-item required">
                        <label>岗位类型</label>
                        <select id="empPositionType" onchange="loadPositionCode()">
                            <option value="">请选择岗位类型</option>
                        </select>
                    </div>
                    
                    <div class="form-item">
                        <label>岗位编号</label>
                        <input type="text" id="empPositionCode" readonly style="background-color: #f5f7fa;">
                    </div>
                    
                    <div class="form-item required">
                        <label>入职时间</label>
                        <input type="month" id="empHireDate" onchange="generateEmployeeNo()">
                    </div>
                    
                    <div class="form-item">
                        <label>员工编号（自动生成）</label>
                        <input type="text" id="empNo" readonly style="background-color: #f5f7fa;">
                    </div>
                    
                    <div class="form-item required">
                        <label>薪资</label>
                        <input type="number" id="empSalary" placeholder="请输入薪资" step="0.01" min="0">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" onclick="closeModal()">取消</button>
                <button class="btn btn-primary" onclick="saveEmployee()">保存</button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 1;
        let totalRecords = 0;
        let isEditMode = false;
        const contextPath = window.location.pathname.substring(0, window.location.pathname.indexOf("/pages"));
        let isLoggedIn = false; // 登录状态标记

        // 检查登录状态
        function checkLogin() {
            if (!isLoggedIn) {
                alert('您尚未登录，请先登录！');
                window.location.href = contextPath + '/login.html';
                return false;
            }
            return true;
        }

        // 跳转到登录页面
        function goToLogin() {
            window.location.href = contextPath + '/login.html';
        }

        // 更新用户界面显示
        function updateUIForLoginStatus(loggedIn, username) {
            if (loggedIn) {
                // 已登录
                document.getElementById('notLoggedIn').style.display = 'none';
                document.getElementById('loggedIn').style.display = 'flex';
                document.getElementById('username').textContent = '欢迎，' + (username || 'admin');
            } else {
                // 未登录
                document.getElementById('notLoggedIn').style.display = 'flex';
                document.getElementById('loggedIn').style.display = 'none';
            }
        }

        // 页面加载
        window.onload = function() {
            // 检查登录状态 - 尝试访问一个需要登录的接口
            fetch(contextPath + '/employee/list?page=1&size=1', {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                if (response.status === 401) {
                    // 未登录
                    isLoggedIn = false;
                    updateUIForLoginStatus(false);
                } else if (response.ok) {
                    // 已登录
                    isLoggedIn = true;
                    // 从session获取用户名（假设在登录时存储）
                    const username = sessionStorage.getItem('username') || 'admin';
                    updateUIForLoginStatus(true, username);
                    // 加载数据
                    loadPositionTypes();
                    loadEmployees();
                }
                return response.ok ? response.json() : null;
            })
            .catch(error => {
                console.error('登录状态检查失败:', error);
                isLoggedIn = false;
                updateUIForLoginStatus(false);
            });
        };

        // 加载岗位类型（用于查询和下拉框）
        function loadPositionTypes() {
            fetch(contextPath + '/option/category?category=岗位类型')
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200 && result.data) {
                        const searchSelect = document.getElementById('searchPositionType');
                        const empSelect = document.getElementById('empPositionType');
                        
                        result.data.forEach(option => {
                            searchSelect.innerHTML += `<option value="${option.name}">${option.name}</option>`;
                            empSelect.innerHTML += `<option value="${option.name}" data-code="${option.value}">${option.name}</option>`;
                        });
                    }
                });
        }

        // 加载岗位编号
        function loadPositionCode() {
            const typeSelect = document.getElementById('empPositionType');
            const selectedOption = typeSelect.options[typeSelect.selectedIndex];
            const positionCode = selectedOption.getAttribute('data-code') || '';
            document.getElementById('empPositionCode').value = positionCode;
            generateEmployeeNo();
        }

        // 生成员工编号
        function generateEmployeeNo() {
            const positionCode = document.getElementById('empPositionCode').value;
            const hireDate = document.getElementById('empHireDate').value;
            
            if (!positionCode || !hireDate) {
                return;
            }
            
            // 将月份格式转换为日期格式（取当月第一天）
            const dateStr = hireDate + '-01';
            
            fetch(contextPath + `/employee/generateEmpNo?positionCode=${positionCode}&hireDate=${dateStr}`)
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        document.getElementById('empNo').value = result.data;
                    }
                });
        }

        // 加载员工列表
        function loadEmployees() {
            const params = new URLSearchParams({
                pageNum: currentPage,
                pageSize: pageSize,
                name: document.getElementById('searchName').value || '',
                phone: document.getElementById('searchPhone').value || '',
                gender: document.getElementById('searchGender').value || '',
                positionType: document.getElementById('searchPositionType').value || '',
                hireDateStart: document.getElementById('searchHireDateStart').value || '',
                hireDateEnd: document.getElementById('searchHireDateEnd').value || '',
                salaryMin: document.getElementById('searchSalaryMin').value || '',
                salaryMax: document.getElementById('searchSalaryMax').value || ''
            });

            fetch(contextPath + '/employee/list?' + params)
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        displayEmployees(result.data.list);
                        updatePagination(result.data.total);
                    } else {
                        alert('加载失败：' + result.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载失败，请稍后重试');
                });
        }

        // 显示员工列表
        function displayEmployees(employees) {
            const tbody = document.getElementById('employeeTableBody');
            
            if (!employees || employees.length === 0) {
                tbody.innerHTML = '<tr><td colspan="10" class="empty-data">暂无数据</td></tr>';
                return;
            }
            
            let html = '';
            employees.forEach(emp => {
                const hireDate = emp.hireDate ? new Date(emp.hireDate).toLocaleDateString('zh-CN') : '';
                html += `
                    <tr>
                        <td><input type="checkbox" class="select-item" value="${emp.id}"></td>
                        <td>${emp.empNo || ''}</td>
                        <td>${emp.name || ''}</td>
                        <td>${emp.age || ''}</td>
                        <td>${emp.gender || ''}</td>
                        <td>${emp.phone || ''}</td>
                        <td>${hireDate}</td>
                        <td>${emp.positionType || ''}</td>
                        <td>¥${emp.salary ? parseFloat(emp.salary).toFixed(2) : '0.00'}</td>
                        <td class="table-actions">
                            <button class="btn btn-primary" onclick="editEmployee('${emp.id}')">编辑</button>
                            <button class="btn btn-danger" onclick="deleteEmployee('${emp.id}')">删除</button>
                        </td>
                    </tr>
                `;
            });
            tbody.innerHTML = html;
        }

        // 更新分页信息
        function updatePagination(total) {
            totalRecords = total;
            totalPages = Math.ceil(total / pageSize);
            
            document.getElementById('currentPageDisplay').textContent = currentPage;
            document.getElementById('totalPagesDisplay').textContent = totalPages;
            document.getElementById('totalRecordsDisplay').textContent = totalRecords;
        }

        // 切换页码
        function changePage(page) {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            if (page < 1 || page > totalPages || page === currentPage) {
                return;
            }
            currentPage = page;
            loadEmployees();
        }

        // 查询
        function searchEmployees() {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            currentPage = 1;
            loadEmployees();
        }

        // 重置查询
        function resetSearch() {
            document.getElementById('searchName').value = '';
            document.getElementById('searchPhone').value = '';
            document.getElementById('searchGender').value = '';
            document.getElementById('searchPositionType').value = '';
            document.getElementById('searchHireDateStart').value = '';
            document.getElementById('searchHireDateEnd').value = '';
            document.getElementById('searchSalaryMin').value = '';
            document.getElementById('searchSalaryMax').value = '';
            searchEmployees();
        }

        // 显示新增模态框
        function showAddModal() {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            isEditMode = false;
            document.getElementById('modalTitle').textContent = '新增员工';
            document.getElementById('employeeForm').reset();
            document.getElementById('employeeId').value = '';
            document.getElementById('empNo').value = '';
            document.getElementById('empPositionCode').value = '';
            document.querySelector('input[name="gender"][value="男"]').checked = true;
            document.getElementById('employeeModal').classList.add('show');
        }

        // 编辑员工
        function editEmployee(id) {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            isEditMode = true;
            document.getElementById('modalTitle').textContent = '编辑员工';
            
            fetch(contextPath + `/employee/detail?id=${id}`)
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        const emp = result.data;
                        document.getElementById('employeeId').value = emp.id;
                        document.getElementById('empName').value = emp.name;
                        document.getElementById('empAge').value = emp.age;
                        document.querySelector(`input[name="gender"][value="${emp.gender}"]`).checked = true;
                        document.getElementById('empPhone').value = emp.phone;
                        document.getElementById('empPositionType').value = emp.positionType;
                        document.getElementById('empPositionCode').value = emp.positionCode;
                        document.getElementById('empNo').value = emp.empNo;
                        document.getElementById('empSalary').value = emp.salary;
                        
                        // 转换日期格式
                        if (emp.hireDate) {
                            const date = new Date(emp.hireDate);
                            const month = String(date.getMonth() + 1).padStart(2, '0');
                            document.getElementById('empHireDate').value = `${date.getFullYear()}-${month}`;
                        }
                        
                        document.getElementById('employeeModal').classList.add('show');
                    } else {
                        alert('加载失败：' + result.message);
                    }
                });
        }

        // 保存员工
        function saveEmployee() {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            // 表单验证
            const name = document.getElementById('empName').value.trim();
            const age = document.getElementById('empAge').value;
            const gender = document.querySelector('input[name="gender"]:checked').value;
            const phone = document.getElementById('empPhone').value.trim();
            const positionType = document.getElementById('empPositionType').value;
            const positionCode = document.getElementById('empPositionCode').value;
            const hireDate = document.getElementById('empHireDate').value;
            const salary = document.getElementById('empSalary').value;
            
            if (!name) {
                alert('请输入姓名');
                return;
            }
            if (!age || age < 18 || age > 100) {
                alert('年龄必须在18-100之间');
                return;
            }
            if (!phone) {
                alert('请输入手机号');
                return;
            }
            if (!/^1[3-9]\d{9}$/.test(phone)) {
                alert('手机号格式不正确');
                return;
            }
            if (!positionType) {
                alert('请选择岗位类型');
                return;
            }
            if (!hireDate) {
                alert('请选择入职时间');
                return;
            }
            if (!salary || salary <= 0) {
                alert('请输入有效的薪资');
                return;
            }
            
            // 转换日期格式
            const dateStr = hireDate + '-01';
            
            const url = isEditMode ? contextPath + '/employee/update' : contextPath + '/employee/add';
            const params = new URLSearchParams({
                name: name,
                age: age,
                gender: gender,
                phone: phone,
                positionType: positionType,
                positionCode: positionCode,
                hireDate: dateStr,
                salary: salary
            });
            
            if (isEditMode) {
                params.append('id', document.getElementById('employeeId').value);
            }
            
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: params
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    alert(isEditMode ? '更新成功！' : '新增成功！员工编号：' + result.data);
                    closeModal();
                    loadEmployees();
                } else {
                    alert('保存失败：' + result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('保存失败，请稍后重试');
            });
        }

        // 删除员工
        function deleteEmployee(id) {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            if (!confirm('确定要删除该员工吗？')) {
                return;
            }
            
            fetch(contextPath + '/employee/delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'id=' + id
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    alert('删除成功！');
                    loadEmployees();
                } else {
                    alert('删除失败：' + result.message);
                }
            });
        }

        // 批量删除
        function deleteBatch() {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            const checkboxes = document.querySelectorAll('.select-item:checked');
            if (checkboxes.length === 0) {
                alert('请选择要删除的员工');
                return;
            }
            
            if (!confirm(`确定要删除选中的${checkboxes.length}个员工吗？`)) {
                return;
            }
            
            const ids = Array.from(checkboxes).map(cb => cb.value).join(',');
            
            fetch(contextPath + '/employee/deleteBatch', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'ids=' + ids
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    alert('批量删除成功！');
                    document.getElementById('selectAll').checked = false;
                    loadEmployees();
                } else {
                    alert('批量删除失败：' + result.message);
                }
            });
        }

        // 全选/取消全选
        function toggleSelectAll() {
            const selectAll = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.select-item');
            checkboxes.forEach(cb => cb.checked = selectAll.checked);
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('employeeModal').classList.remove('show');
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                // 清除sessionStorage中的用户名
                sessionStorage.removeItem('username');
                // 跳转到登出接口
                window.location.href = contextPath + '/logout';
            }
        }
    </script>
</body>
</html>
